<template>
  <el-card>

    <el-button type="primary" @click="addUser" style="margin-bottom: 8px">添加管理员</el-button>
    <el-table :data="users" style="width: 100%" border>
      <el-table-column label="序号" prop="id" width="100px"/>
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="姓名" prop="realName" />
      <el-table-column label="角色" prop="roleName" />
      <el-table-column label="审核人" prop="reviewer" width="100px">
        <template v-slot="scope">
          {{ scope.row.reviewer ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" />
      <el-table-column width="150px" label="操作">
        <template #default="scope">
          <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEditing ? '编辑管理员' : '添加管理员'">
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.realName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" placeholder="请输入密码（不修改可留空）"></el-input>
        </el-form-item>

        <el-form-item label="角色">
          <el-select v-model="form.roleId" placeholder="请选择角色">
            <el-option
                v-for="role in roles"
                :key="role.id"
                :label="role.name"
                :value="role.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="审核人">
          <el-switch v-model="form.reviewer" active-text="是" inactive-text="否" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { getAdmins, createAdmin, updateAdmin, deleteAdmin } from '@/apps/admin/utils/adminApi.ts'
import { getRoles } from '@/apps/admin/utils/rolesApi.js'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const form = ref({
  username: '',
  realName: '',
  password: '',
  email: '',
  roleId: null,
  reviewer: false
})

const formRef = ref(null)
const users = ref([])
const roles = ref([])

const isEditing = ref(false)
const editingId = ref(null)

// 打开添加对话框
const addUser = () => {
  dialogVisible.value = true
  isEditing.value = false
  editingId.value = null
  form.value = {
    username: '',
    realName: '',
    password: '',
    email: '',
    roleId: null
  }
}

// 打开编辑对话框
const editUser = (user) => {
  console.log(user)
  dialogVisible.value = true
  isEditing.value = true
  editingId.value = user.id
  form.value = {
    id: user.id,
    username: user.username,
    realName: user.realName,
    password: '',
    // email: user.email || '',
    roleId: user.roleId,
    reviewer: user.reviewer
  }
}

// 提交表单
const submitForm = async () => {
  try {

    const userData = form.value;
    console.log(userData)
    if (userData.password === ''){
      userData.password = null;
    }
    // if (form.value.password) {
    //   userData.password = form.value.password
    // }

    if (isEditing.value) {
      const res = await updateAdmin(userData)
      if (res.code === 200) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        await fetchAdmins()
      } else {
        ElMessage.error(res.msg)
      }
    } else {
      const res = await createAdmin(userData)
      if (res["code"] === 200) {
        ElMessage.success('创建成功')
        dialogVisible.value = false
        await fetchAdmins()
        //users.value.push(res.data)

      } else {
        ElMessage.error(res["msg"])
      }
    }
  } catch (err) {
    console.error('操作失败:', err)
    ElMessage.error(err?.response?.data?.msg || '操作失败')
  }
}

// 删除管理员
const deleteUser = async (user) => {
  try {
    const res = await deleteAdmin({ adminId: user.id })
    if (res["code"] === 200) {
      ElMessage.success('删除成功')
      users.value = users.value.filter(u => u.id !== user.id)
    } else {
      ElMessage.error(res["msg"])
    }
  } catch (err) {
    console.error('删除失败:', err)
    ElMessage.error('删除失败')
  }
}

// 获取管理员和角色
const fetchAdmins = async () => {
  const res = await getAdmins()
  users.value = res.data
}

onMounted(async () => {
  const roleRes = await getRoles()
  roles.value = roleRes.data
  await fetchAdmins()
})
</script>
